package com.liushuai.eas.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liushuai.eas.common.MD5Util;
import com.liushuai.eas.common.OriginPsw;
import com.liushuai.eas.common.Result;
import com.liushuai.eas.pojo.Administrator;
import com.liushuai.eas.service.AdministratorImp;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;

@RestController
@RequestMapping("/administrator")
public class AdministratorController {

    @Resource
    private AdministratorImp administratorImp;

    @PostMapping
    public Result<Administrator> add(@RequestBody Administrator administrator){
        //初始化密码
        administrator.setPassword(MD5Util.md5(OriginPsw.getOriginPassword()));
        if (administratorImp.insert(administrator)!=1)
            return Result.fail();
        return Result.success(administrator);
    }

    @PutMapping
    public Result<Administrator> update(@RequestBody Administrator administrator){
        administrator.setPassword(MD5Util.md5(administrator.getPassword()));
        if (administratorImp.updateById(administrator)!=1)
            return Result.fail(administrator);
        return Result.success(administrator);
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        Page<Administrator> administratorPage = administratorImp.selectPage(new Page<Administrator>(pageNum, pageSize), Wrappers.<Administrator>lambdaQuery().like(Administrator::getName, search));
        return Result.success("数据加载成功",administratorPage);
    }

    @DeleteMapping
    public Result<Administrator> delete(@RequestBody Administrator administrator){
        if (administratorImp.deleteById(administrator)!=1)
            return Result.fail(administrator);
        return Result.success(administrator);
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody Administrator administrator){
        administrator.setPassword(MD5Util.md5(administrator.getPassword()));
        Administrator admin = administratorImp.selectOne(Wrappers.<Administrator>lambdaQuery().eq(Administrator::getName, administrator.getName()).eq(Administrator::getPassword, administrator.getPassword()));
        if (admin==null){
            return Result.fail("用户名或密码错误");
        }
        HashMap<Object, Object> map = new HashMap<>();
        map.put("user",admin);
        return Result.success("登录成功，您好！尊贵的"+admin.getName(),map);
    }

}
